//#pragma warning(disable: 4201)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <mmsystem.h>
#include "frametimer.h"

//#pragma comment(lib, "winmm.lib")

namespace gecko
{

FrameTimer::FrameTimer()
{
    if(!QueryPerformanceFrequency((LARGE_INTEGER *) &m_qwTicksPerSec))
        m_qwTicksPerSec = 1000;

    m_ticksPerSec  = (float) (__int64) m_qwTicksPerSec;
}

void FrameTimer::Start()
{
	float framesPerSec = 30.0f;
    m_framesPerSec = framesPerSec;
    m_secsPerFrame = 1.0f / framesPerSec;
    m_qwTicksPerFrame = m_qwTicksPerSec / (__int64) framesPerSec;

    m_qwTicks = GetTicks();
}

void FrameTimer::Frame()
{
    __int64 qw;
    qw = GetTicks();


    if(qw != m_qwTicks)
    {
        m_qwTicksPerFrame = qw - m_qwTicks;
        m_qwTicks = qw;

        m_framesPerSec = 0.0f * m_framesPerSec + 1.0f * (m_ticksPerSec / (float) (__int64) m_qwTicksPerFrame);

        if(m_framesPerSec < 1.0f)
            m_framesPerSec = 1.0f;

        m_secsPerFrame = 1.0f / m_framesPerSec;
    }
}

__int64 FrameTimer::GetTicks()
{
    __int64 qw;

    if(QueryPerformanceCounter((LARGE_INTEGER *) &qw))
    {
        while(!qw)
            QueryPerformanceCounter((LARGE_INTEGER *) &qw);
    }
    else
    {
        qw = (__int64) timeGetTime();
    }

    return qw;
}

}
